package com.huaxiafinance.management.util;


import com.huaxiafinance.management.model.User;
import org.apache.log4j.Logger;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.io.IOException;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Map;


public class DesUtil
{

    private static final Logger logger = Logger.getLogger(DesUtil.class);

    private static final String DES = "DES";

    /**
     * Description 根据键值对进行加密
     *
     * @param data
     * @param key
     *            加密键byte数组
     * @return String
     * @throws Exception
     */
    public static String encrypt(String data, String key)
        throws Exception
    {
        byte[] bt = encrypt(data.getBytes("utf-8"), key.getBytes("utf-8"));
        String strs = new BASE64Encoder().encode(bt);
        return strs;
    }

    /**
     * Description 根据键值对进行解密
     *
     * @param data
     * @param key
     *            加密键byte数组
     * @return String
     * @throws IOException
     * @throws Exception
     */
    public static String decrypt(String data, String key)
        throws IOException,
        Exception
    {
        if (data == null)
        {
            return null;
        }
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] buf = decoder.decodeBuffer(data);
        byte[] bt = decrypt(buf, key.getBytes("utf-8"));
        return new String(bt, "utf-8");
    }

    /**
     * Description 根据键值对进行加密
     *
     * @param data
     * @param key
     *            加密键byte数组
     * @return byte[]
     * @throws Exception
     */
    private static byte[] encrypt(byte[] data, byte[] key)
        throws Exception
    {
        // 生成�?��可信任的随机数源
        SecureRandom sr = new SecureRandom();

        // 从原始密钥数据创建DESKeySpec对象
        DESKeySpec dks = new DESKeySpec(key);

        // 创建�?��密钥工厂，然后用它把DESKeySpec转换成SecretKey对象
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
        SecretKey securekey = keyFactory.generateSecret(dks);

        // Cipher对象实际完成加密操作
        Cipher cipher = Cipher.getInstance(DES);

        // 用密钥初始化Cipher对象
        cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);

        return cipher.doFinal(data);
    }

    /**
     * Description 根据键值对进行解密
     *
     * @param data
     * @param key
     *            加密键byte数组
     * @return byte[]
     * @throws Exception
     */
    private static byte[] decrypt(byte[] data, byte[] key)
        throws Exception
    {
        // 生成�?��可信任的随机数源
        SecureRandom sr = new SecureRandom();

        // 从原始密钥数据创建DESKeySpec对象
        DESKeySpec dks = new DESKeySpec(key);

        // 创建�?��密钥工厂，然后用它把DESKeySpec转换成SecretKey对象
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
        SecretKey securekey = keyFactory.generateSecret(dks);

        // Cipher对象实际完成解密操作
        Cipher cipher = Cipher.getInstance(DES);

        // 用密钥初始化Cipher对象
        cipher.init(Cipher.DECRYPT_MODE, securekey, sr);

        return cipher.doFinal(data);
    }

    /**
     * 设定安全的密码，生成随机的salt并经过1024次 sha-1 hash
     *
     * @param user
     *            用户
     */
    public static void entryptPassword(User user)
    {
        String salt = RandomString.randomAlpha(
            Integer.parseInt(Global.getConfig("shiro.saltSize")));
        String pass = null;
        try
        {
            pass = DesUtil.encrypt(user.getPassword(), salt);
        }
        catch (Exception e)
        {
            logger.error("错误++++++" + e);
        }
        user.setSalt(salt);
        user.setPassword(pass);
    }


    /**
     * query parameter to map
     *
     * @param parameter=chrome-instant&ion=1
     * @return {"sourceid":"chrome-instant", "ion":"1"}
     */
    public static Map<String, String> parameterToMap(String parameter)
    {
        Map<String, String> map = new HashMap<String, String>();
        String[] paraArray = parameter.split("@");
        for (String pair : paraArray)
        {
            String key = pair.substring(0, pair.indexOf("="));
            String value = pair.substring(pair.indexOf("=") + 1);
            map.put(key, value);
        }
        return map;
    }
}
